﻿using System;
using System.Threading.Tasks;
using DotNetCore.CAP;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace K9Nano.Events.Cap
{
    public class CapEventBus : EventBus, ICapSubscribe
    {
        public const string CapEventName = "k9.eventbus";

        private readonly ICapPublisher _capBus;

        public CapEventBus(IServiceProvider serviceProvider) : base(serviceProvider)
        {
            _capBus = serviceProvider.GetRequiredService<ICapPublisher>();
        }

        public override void Trigger(string eventName, IEventData eventData, bool internalOnly)
        {
            var data = new EventDataWrapper(eventName, eventData, Source);
            if (internalOnly)
            {
                base.Trigger(eventName, eventData, true);
            }
            else
            {
                _capBus.Publish(CapEventName, data);
            }
        }

        public override async ValueTask TriggerAsync(string eventName, IEventData eventData, bool internalOnly)
        {
            var data = new EventDataWrapper(eventName, eventData, Source);
            if (internalOnly)
            {
                await base.TriggerAsync(eventName, eventData, true);
            }
            else
            {
                await _capBus.PublishAsync(CapEventName, data);
            }
        }

        [CapSubscribe(CapEventBus.CapEventName)]
        public void OnReceive(EventDataWrapper data)
        {
            Logger.LogDebug($"received: {data.Data}");
            // 触发本地的事件
            EventBlock.Post(data);
        }
    }
}